package com.yy.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @Author: lyy
 * Date: 2021/12/20 15:33
 */
@Component
public class RedisUtil {

	private static RedisTemplate redisTemplate;

	@Autowired
	public void setRedisTemplate(RedisTemplate redisTemplate){
		RedisUtil.redisTemplate = redisTemplate;
	}

	/**
	 * 往redis中存值，无过期时间
	 * @param key
	 * @param value
	 */
	public static void set(String key, Object value){
		redisTemplate.opsForValue().set(key, value);
	}

	/**
	 * 往redis中存值，并设置过期时间，默认单位为秒
	 * @param key
	 * @param value
	 * @param expireTime
	 */
	public static void set(String key, Object value, long expireTime){
		set(key, value, expireTime, TimeUnit.SECONDS);
	}

	/**
	 * 往redis中存值，并设置过期时间，时间单位
	 * @param key
	 * @param value
	 * @param expireTime
	 * @param timeUnit
	 */
	public static void set(String key, Object value, long expireTime, TimeUnit timeUnit){
		set(key, value);
		redisTemplate.expire(key, expireTime, timeUnit);
	}

	/**
	 * 获取值
	 * @param key
	 * @return
	 */
	public static Object get(String key){
		return redisTemplate.opsForValue().get(key);
	}

	/**
	 * 往redis中存储list
	 * @param key
	 * @param value
	 */
	public static void setList(String key, Object value){
		redisTemplate.opsForList().leftPush(key, value);
	}

	/**
	 * 从redis中获取list
	 * @param key
	 * @return
	 */
	public static Object getList(String key){
		 return redisTemplate.opsForList().leftPop(key);
	}

	/**
	 * 往redis中存储map
	 * @param key
	 * @param map
	 */
	public static void setHash(String key, Map map){
		redisTemplate.opsForHash().putAll(key, map);
	}

	/**
	 * 从redis中取map
	 * @param key
	 * @return
	 */
	public static List getHash(String key){
		Set keys = redisTemplate.opsForHash().keys(key);
		return redisTemplate.opsForHash().multiGet(key, keys);
	}

	/**
	 * 从redis中获取map的指定键
	 * @param key
	 * @param hashKey
	 * @return
	 */
	public static Object getHash(String key, String hashKey){
		return redisTemplate.opsForHash().get(key, hashKey);
	}

	/**
	 * 往redis中存储set
	 * @param key
	 * @param value
	 */
	public static void add(String key, Object value){
		redisTemplate.opsForSet().add(key, value);
	}

	/**
	 * 从redis中获取set
	 * @param key
	 * @return
	 */
	public static Set getMembers(String key){
		return redisTemplate.opsForSet().members(key);
	}

	/**
	 * 从redis中存储 ZSet
	 * @param key
	 * @param value
	 */
	public static void zAdd(String key, Set value){
		redisTemplate.opsForZSet().add(key, value);
	}

	/**
	 * 从redis中获取 ZSet
	 * @param key
	 * @return
	 */
	public static Set zGet(String key){
		return redisTemplate.opsForZSet().range(key, 0, -1);
	}
}
